package com.atguigu.com.exam;

/**
 * @author xbd
 * @create 2021-05-23 15:20
 */

class Clink{
    private int num = 0;
    private int count = 0;

    public synchronized void addNum(){
        if(num < 4){
            num++;
            System.out.println(Thread.currentThread().getName() + ":开始生产" + num);
            notify();
        }else{
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void subNum(){
        if(num > 0 && count < 10){
            num--;
            count++;
            System.out.println(Thread.currentThread().getName() + ":开始消费" + num + "共计：" + count);
            notify();
        }else{
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class addEnd extends Thread{

    private Clink clink;
    public addEnd(Clink clink){
        this.clink = clink;
    }
    @Override
    public void run() {
        System.out.println("开始生产产品。。。");

        while (true){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            
            clink.addNum();
        }
    }
}

class subEnd extends Thread{

    private Clink clink;
    public subEnd(Clink clink){
        this.clink = clink;
    }
    @Override
    public void run() {
        System.out.println("开始消费产品。。。");

        while (true){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            clink.subNum();
        }
    }
}

public class ManyLine {
    public static void main(String[] args) {
        Clink c1 = new Clink();
        addEnd a1 = new addEnd(c1);
        subEnd s1 = new subEnd(c1);

        a1.setName("生产者");
        s1.setName("消费者");

        a1.start();
        s1.start();
    }
}
